from PIL import Image
import sys


def fill_image(image):
    width, height = image.size
    image_length = max([width, height])
    new_image = Image.new(image.mode, (image_length, image_length), color='white')

    if width > height:
        new_image.paste(image, (0, int((image_length - height) / 2)))
    else:
        new_image.paste(image, (int((image_length - width) / 2), 0))
    return new_image


def cut_image(image, patches=9):
    sig_patches = 0
    if patches % 2 == 0:
        sig_patches = int(patches / 2)
    elif patches % 3 == 0:
        sig_patches = int(patches / 3)
    else:
        raise RuntimeError("only used for *2 or *3!")

    width, height = image.size
    item_width = int(width / sig_patches)
    box_list = []
    count = 0
    for j in range(sig_patches):
        for i in range(sig_patches):
            count += 1
            box = (i * item_width, j * item_width, (i + 1) * item_width, (j + 1) * item_width)
            box_list.append(box)
    image_list = [image.crop(box) for box in box_list]
    return image_list


def save_images(image_list):
    index = 1
    for image in image_list:
        image.save('result/' + str(index) + '.jpg')
        index += 1


if __name__ == '__main__':
    file_path = "./dog.jpg"
    # 打开图像
    image = Image.open(file_path)
    # 将图像转为正方形，不够的地方补充为白色底色
    image = fill_image(image)
    # 分为图像
    image_list = cut_image(image,12)
    # 保存图像
    save_images(image_list)
